package lk.icta.common.web.action;

import lk.icta.common.entity.Document;
import lk.icta.common.entity.DocumentCategory;
import lk.icta.common.service.DocumentManagementService;
import lk.icta.core.entity.ModuleType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Mahesha Kalpanie
 */
public class DocumentUploadAction extends BaseAction {

    private static final Logger logger = LoggerFactory.getLogger(DocumentUploadAction.class);

    //protected File fileKml;
    //protected String fileKmlContentType;
    //protected String fileKmlFileName;

    protected File[] files;
    protected String[] filesFileName; // The uploaded file name and path
    protected String[] filesContentType;
    //protected String[] nameOfDocument;
    protected List<Document> documentList;
    protected List<Document> kmlDocumentList;
    protected long documentId;
    protected InputStream inputStream;
    protected String contentType;
    protected String fileName;
    protected List<DocumentCategory> documentCategoryList = new ArrayList<DocumentCategory>();
    protected int[] documentCategory;
    protected List<Long> deleteDocList = new ArrayList<Long>();

    protected final DocumentManagementService documentManagementService;

    public DocumentUploadAction(DocumentManagementService documentManagementService) {
        this.documentManagementService = documentManagementService;
         logger.debug("DocumentUploadAction");
    }

    /* Display Document List */

    protected void populateUploadedFiles(long id, ModuleType moduleType) {
        logger.debug("Populating uploaded files {} - ", user.getUsername());
        try {
            List<Document> docList = documentManagementService.getDocumentsByModuleAndModuleId(getUser(), moduleType, id);

            if (docList != null) {
                if (documentList == null) {
                    documentList = new ArrayList<Document>();
                }
                for (Document doc : docList) {
                    /*  if (".kml".equals(doc.getExtension())) {
                     if (kmlDocumentList == null) {
                         kmlDocumentList = new ArrayList<Document>();
                     }
                     kmlDocumentList.add(doc);
                 } else { */

                    documentList.add(doc);
                    //  }
                }
                logger.debug("size of document list - {} ", docList.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected List<Document> getUploadedfileList(ModuleType moduleType) {
        logger.debug("getting uploaded files -----------------------------------------");
        List<Document> docList = new ArrayList<Document>();
        if (files != null) {
            logger.debug("Size of file list ...... {}", files.length);
            for (int i = 0; i < files.length; i++) {
                if (files[i] != null) {
                    Document document = new Document();

                    DocumentCategory docCategory = new DocumentCategory();
                    if (documentCategory != null && documentCategory[i] > 0) {
                        docCategory.setId(documentCategory[i]);
                    } /*else {
                       docCategory.setId(AppConstants.KML_DOCUMENT_CATEGORY);
                    }  */
                    document.setDocumentCategory(docCategory);

                    document.setContentType(filesContentType[i]);
                    document.setModuleType(moduleType);
                    document.setFile(files[i]);
                    document.setFileName(filesFileName[i]);

                    //  if (nameOfDocument[i] == null || ("".equals(nameOfDocument[i]))) {
                    int dotPos = filesFileName[i].indexOf('.');
                    if (dotPos != -1) {
                        document.setDocumentName(filesFileName[i].substring(0, dotPos));
                    } else {
                        document.setDocumentName(filesFileName[i]);
                    }
                    /*} else {
                        document.setDocumentName(nameOfDocument[i]);
                    }    */
                    docList.add(document);
                }
            }
            //adding kml files
            /* if (fileKml != null) {
              //TODO: check the contenttype and verify kml file
              logger.debug("uploading kml file---------------------------------------- ");
              Document document = new Document();
              document.setDocumentName(fileKmlFileName);

              DocumentCategory docCategory = new DocumentCategory();
              docCategory.setId(AppConstants.KML_DOCUMENT_CATEGORY);
              document.setDocumentCategory(docCategory);

              document.setContentType(fileKmlContentType);
              document.setModuleType(moduleType);
              document.setFile(fileKml);
              document.setFileName(fileKmlFileName);
              docList.add(document);
          }  */
        }
        return docList;
    }
    /*
public String getFileStream() {
   logger.debug("file---------------------------------------- {}", fileKml.toString());
   logger.debug("file kml content type---------- {}", fileKmlContentType);
   logger.debug("file kml file name --------- {}", fileKmlFileName);
   contentType = fileKmlContentType;
   fileName = fileKmlFileName;
   try {
       inputStream = new FileInputStream(fileKml);
   } catch (FileNotFoundException e) {
       e.printStackTrace();
       addActionError("File Not Found");
       return ERROR;
   }
   return SUCCESS;
}     */

    public String openFile() {
        try {
            Document document = documentManagementService.getDocumentById(getUser(), documentId);
            logger.debug("document found with id : {}", document.getId());

            contentType = document.getContentType();

            if (document.getExtension() != null) {
                fileName = document.getDocumentName() + document.getExtension();
            } else {
                fileName = document.getDocumentName();
            }

            fileName = fileName.replaceAll(" ", "");


            //  inputStream = new ByteArrayInputStream(AlfrescoUtil.downloadFile(document));

            if (document.getExtension() != null) {
                inputStream = new FileInputStream(new File(document.getLocation() + document.getId() + document.getExtension().toLowerCase()));
            } else {
                inputStream = new FileInputStream(new File(document.getLocation() + document.getId()));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            addActionError("File Not Found");
            return ERROR;
        } catch (Exception e) {
            e.printStackTrace();
            addActionError("File can not be opened");
            return ERROR;
        }
        return SUCCESS;
    }

    public List<DocumentCategory> findDocumentCategoryList(ModuleType moduleType) {
        //toDO : Search doc list by module id
        logger.debug("find Document Category List");
        documentCategoryList = documentManagementService.getDocumentCategoryListByModuleId(user, moduleType);
        if (documentCategoryList != null) {
            logger.debug("document category list size  - {}  ", documentCategoryList.size());
        }
        return documentCategoryList;
    }

    public void deleteDocument() {
        logger.debug("delete Document  List");
        logger.debug("Delete documents list : {}", deleteDocList.size());
        for (long dId : deleteDocList) {
            logger.debug("Delete doc id: {} \n", dId);
            Document document = documentManagementService.getDocumentById(getUser(), dId);
            if (document != null) {
                if (deleteServerDoc(document)) {
                    documentManagementService.deleteDocumentById(getUser(), dId);
                }

            }
        }
    }

    private boolean deleteServerDoc(Document doc) {
        try {

            String extension = doc.getExtension();
            if (extension == null) {
                extension = "";
            }
            logger.debug("File Path :{}", doc.getLocation() + doc.getModuleId() + extension);
            File file = new File(doc.getLocation() + doc.getId() + extension);
            if (file.delete()) {
                logger.debug("File is deleted");
                return true;
            } else {
                logger.debug("File Delete operation is failed.");
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("File Delete operation Exception {}:", e.getMessage());
            return false;
        }
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public File[] getFiles() {
        return files;
    }

    public void setFiles(File[] files) {
        this.files = files;
    }

    public String[] getFilesFileName() {
        return filesFileName;
    }

    public void setFilesFileName(String[] filesFileName) {
        this.filesFileName = filesFileName;
    }

    public String[] getFilesContentType() {
        return filesContentType;
    }

    public void setFilesContentType(String[] filesContentType) {
        this.filesContentType = filesContentType;
    }

    public List<Document> getDocumentList() {
        return documentList;
    }

    public void setDocumentList(List<Document> documentList) {
        this.documentList = documentList;
    }

    public long getDocumentId() {
        return documentId;
    }

    public void setDocumentId(long documentId) {
        this.documentId = documentId;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public List<Document> getKmlDocumentList() {
        return kmlDocumentList;
    }

    public void setKmlDocumentList(List<Document> kmlDocumentList) {
        this.kmlDocumentList = kmlDocumentList;
    }

    public List<DocumentCategory> getDocumentCategoryList() {
        return documentCategoryList;
    }

    public void setDocumentCategoryList(List<DocumentCategory> documentCategoryList) {
        this.documentCategoryList = documentCategoryList;
    }

    public int[] getDocumentCategory() {
        return documentCategory;
    }

    public void setDocumentCategory(int[] documentCategory) {
        this.documentCategory = documentCategory;
    }


    public List<Long> getDeleteDocList() {
        return deleteDocList;
    }

    public void setDeleteDocList(List<Long> deleteDocList) {
        this.deleteDocList = deleteDocList;
    }
}
